package cn.hengzhu.main_manager.web.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hengzhu.main_manager.repository.dao.ManageMenuMapper;
import cn.hengzhu.main_manager.repository.dao.ManagePermissionMapper;
import cn.hengzhu.main_manager.repository.dao.ManageRolesMapper;
import cn.hengzhu.main_manager.repository.domain.ManageMenu;
import cn.hengzhu.main_manager.repository.domain.ManageMenuExample;
import cn.hengzhu.main_manager.repository.domain.ManagePermission;
import cn.hengzhu.main_manager.repository.domain.ManagePermissionExample;
import cn.hengzhu.main_manager.repository.domain.ManageRoles;
import cn.hengzhu.main_manager.repository.domain.ManageUser;
import cn.hengzhu.main_manager.repository.param.AddPermissionParam;
import cn.hengzhu.main_manager.repository.vo.ChildrenMenuVO;
import cn.hengzhu.main_manager.repository.vo.MenuListVO;
import cn.hengzhu.main_manager.repository.vo.MenuVO;
import cn.hengzhu.main_manager.repository.vo.TreeBaseVO;
import cn.hengzhu.main_manager.repository.vo.TreeOneVO;
import cn.hengzhu.main_manager.repository.vo.TreeThreeVO;
import cn.hengzhu.main_manager.repository.vo.TreeTwoVO;
import cn.hengzhu.main_manager.utils.UserContext;
import cn.hengzhu.main_manager.utils.ann.SystemControllerLog;

@Controller
@RequestMapping("/main")
public class MainController {

	@Autowired
	private ManageRolesMapper manageRolesMapper;
	@Autowired
	private ManagePermissionMapper managePermissionMapper;
	@Autowired
	private ManageMenuMapper manageMenuMapper;

	/**
	 * 权限的添加
	 */
	@SystemControllerLog(description = "权限的添加")
	@RequestMapping("/addPermission")
	public void addPermission(AddPermissionParam param) {
		String resource = param.getResource();
		ManagePermission managePermission = new ManagePermission();
		managePermission.setCreateTime(new Date());
		managePermission.setName(param.getName());
		managePermission.setParentId(param.getParentId());
		managePermission.setRank(param.getRank());
		managePermission.setResource(resource);
		managePermission.setIsShow(param.getShow());
		String sn = resource.substring(1).replace("/", ":");
		managePermission.setSn(sn);
		managePermissionMapper.insert(managePermission);
	}

	/**
	 * 权限的删除
	 */
	@SystemControllerLog(description = "权限的删除")
	@RequestMapping("/deletePermission")
	public void deletePermission(Integer permissionId) {
		managePermissionMapper.deleteByPrimaryKey(permissionId);
	}

	/**
	 * 权限的修改
	 */
	@SystemControllerLog(description = "权限的修改")
	@RequestMapping("/updatePermission")
	public void updatePermission(AddPermissionParam param) {
		String resource = param.getResource();
		ManagePermission managePermission = new ManagePermission();
		managePermission.setCreateTime(new Date());
		managePermission.setName(param.getName());
		managePermission.setParentId(param.getParentId());
		managePermission.setRank(param.getRank());
		managePermission.setResource(resource);
		managePermission.setIsShow(param.getShow());
		managePermission.setId(param.getId());
		String sn = resource.substring(1).replace("/", ":");
		managePermission.setSn(sn);
		managePermissionMapper.updateByPrimaryKeySelective(managePermission);
	}

	/**
	 * @return 菜单列表
	 */
	@ResponseBody
	@RequestMapping("/getMenu")
	public MenuListVO getMenu() {
		MenuListVO menuListVO = new MenuListVO();
		List<MenuVO> menuList = new ArrayList<>();
		ManageUser user = UserContext.getUser();
		Integer managerId = user.getManagerId();
		String permissionIds = manageRolesMapper.getPermssion(managerId);
		List<String> permissionIdList = Arrays.asList(permissionIds.split(","));

		List<Integer> codesInteger = permissionIdList.stream().map(Integer::parseInt).collect(Collectors.toList());
		ManagePermissionExample example = new ManagePermissionExample();
		example.createCriteria().andIdIn(codesInteger);
		List<ManagePermission> permissionsByIds = managePermissionMapper.selectByExample(example);

		List<Integer> menuIds = new ArrayList<>();
		permissionsByIds.stream().forEach(a -> {
			Integer menuId = a.getMenuId();
			if (menuId != null) {
				menuIds.add(a.getMenuId());
			}
		});
		ManageMenuExample menuExample = new ManageMenuExample();
		menuExample.createCriteria().andIdIn(menuIds);
		List<ManageMenu> menus = manageMenuMapper.selectByExample(menuExample);
		Map<Integer, List<ManageMenu>> childrenMap = menus.stream()
				.collect(Collectors.groupingBy(ManageMenu::getParentId, Collectors.toList()));
		List<Integer> menuParaentIds = menus.stream()
				.collect(Collectors.mapping(ManageMenu::getParentId, Collectors.toList())).stream().distinct()
				.collect(Collectors.toList());
		ManageMenuExample menuParaentExample = new ManageMenuExample();
		menuParaentExample.createCriteria().andIdIn(menuParaentIds);
		List<ManageMenu> parentMenuList = manageMenuMapper.selectByExample(menuParaentExample);
		Map<Integer, String> parentMenuMap = parentMenuList.stream()
				.collect(Collectors.toMap(ManageMenu::getId, ManageMenu::getName));
		menuParaentIds.stream().forEach(paraentId -> {
			MenuVO menuVO = new MenuVO();
			menuVO.setHref("");
			menuVO.setIcon("icon-text");
			menuVO.setTitle(parentMenuMap.get(paraentId));
			List<ManageMenu> childrenList = childrenMap.get(paraentId);
			List<ChildrenMenuVO> childrenMenu = new ArrayList<>();
			childrenList.stream().forEach(a -> {
				ChildrenMenuVO childrenMenuVO = new ChildrenMenuVO();
				childrenMenuVO.setHref(a.getUrl());
				childrenMenuVO.setTitle(a.getName());
				childrenMenu.add(childrenMenuVO);
			});
			menuVO.setChildren(childrenMenu);
			menuList.add(menuVO);
		});
		menuListVO.setContentManagement(menuList);

		return menuListVO;
	}

	@ResponseBody
	@RequestMapping("/getAllTree")
	public List<TreeOneVO> getAllTree() {
		ManageUser user = UserContext.getUser();
		Integer roleId = user.getRoleId();
		ManageRoles permssionByRoleId = manageRolesMapper.selectByPrimaryKey(roleId);
		String permissions = permssionByRoleId.getPermissions();
		List<String> permissionIdList = Arrays.asList(permissions.split(","));

		TreeOneVO treeOneVO = new TreeOneVO();
		List<TreeTwoVO> twoVOList = new ArrayList<>();
		// 查询自己所有的权限
		List<Integer> codesInteger = permissionIdList.stream().map(Integer::parseInt).collect(Collectors.toList());

		ManagePermissionExample example = new ManagePermissionExample();
		example.createCriteria().andIdIn(codesInteger);
		List<ManagePermission> allPermission = managePermissionMapper.selectByExample(example);

		List<Integer> menuIds = allPermission.stream().filter(a -> a.getParentId() == null)
				.collect(Collectors.mapping(ManagePermission::getMenuId, Collectors.toList()));
		
		
		ManageMenuExample childrenMenuExample=new ManageMenuExample();
		childrenMenuExample.createCriteria().andIdIn(menuIds);
		List<ManageMenu> childrenMenuByIds = manageMenuMapper.selectByExample(childrenMenuExample);

		List<Integer> parentMenuIds = childrenMenuByIds.stream()
				.collect(Collectors.mapping(ManageMenu::getParentId, Collectors.toList())).stream().distinct()
				.collect(Collectors.toList());
		
		ManageMenuExample parentMenuExample=new ManageMenuExample();
		parentMenuExample.createCriteria().andIdIn(parentMenuIds);
		List<ManageMenu> parentMenuList = manageMenuMapper.selectByExample(parentMenuExample);
		
		// 拿到末级节点的父节点的父节点的菜单分类
		Map<Integer, List<ManageMenu>> childrenMenuByParentIdMap = childrenMenuByIds.stream()
				.collect(Collectors.groupingBy(ManageMenu::getParentId, Collectors.toList()));
		Map<Integer, ManageMenu> parentMenuByIdMap = parentMenuList.stream()
				.collect(Collectors.toMap(ManageMenu::getId, a -> a));

		// 末级节点的父节点
		// Map<Integer, ManagePermission> parentPermission =
		// allPermission.stream().filter(a -> a.getParentId() == null)
		// .collect(Collectors.toMap(ManagePermission::getId, a -> a));
		// 筛选出所有的末级节点
		Map<Integer, List<ManagePermission>> childrentPermission = allPermission.stream()
				.filter(a -> a.getParentId() != null).collect(Collectors.groupingBy(ManagePermission::getParentId));

		Map<Integer, ManagePermission> collect = allPermission.stream().filter(a -> a.getParentId() == null)
				.collect(Collectors.toMap(ManagePermission::getMenuId, a -> a));

		parentMenuIds.stream().forEach(a -> {
			TreeTwoVO twoVO = new TreeTwoVO();
			ManageMenu manageMenu = parentMenuByIdMap.get(a);
			twoVO.setName(manageMenu.getName());
			List<ManageMenu> childrentMenuList = childrenMenuByParentIdMap.get(a);
			List<TreeThreeVO> threeListVO = new ArrayList<>();
			childrentMenuList.stream().forEach(b -> {
				TreeThreeVO treeThreeVO = new TreeThreeVO();
				ManagePermission managePermission = collect.get(b.getId());
				treeThreeVO.setName(b.getName());
				treeThreeVO.setId(managePermission.getId());

				List<ManagePermission> last = childrentPermission.get(managePermission.getId());
				if (last != null) {
					List<TreeBaseVO> baseList = new ArrayList<>();
					last.stream().forEach(c -> {
						TreeBaseVO baseVO = new TreeBaseVO();
						baseVO.setName(c.getName());
						baseVO.setId(c.getId());
						baseList.add(baseVO);
					});
					treeThreeVO.setChildren(baseList);
				}

				threeListVO.add(treeThreeVO);
			});
			twoVO.setChildren(threeListVO);
			twoVOList.add(twoVO);
		});
		treeOneVO.setChildren(twoVOList);
		List<TreeOneVO> list = new ArrayList<>();
		list.add(treeOneVO);
		return list;

	}

}
